<!-- eslint-disable vue/valid-v-else -->
<template>
  <div class="app-container agricultural-page">
    <!-- 顶部标题和操作区 -->
    <div class="header-section">
      <div class="title-container">
        <h1 class="page-title">农产品</h1>
      </div>
      <div class="toolbar">
        <div class="search-section">
          <el-input
            v-model="searchQuery"
            placeholder="搜索农产品名称、产地或商店..."
            class="search-input"
            clearable
          >
            <template #prefix>
              <i class="el-icon-search"></i>
            </template>
          </el-input>
          <el-button type="primary" icon="el-icon-search" @click="searchAgricultural">搜索</el-button>
        </div>
      </div>
    </div>

    <!-- 筛选区域 -->
    <div class="filter-section">
      <div class="filter-options">
        <el-slider
          v-model="priceRange"
          :min="0"
          :max="200"
          :step="5"
          range
          @change="filterByPrice"
        ></el-slider>
        <span class="price-range-text">价格范围: {{ priceRange[0] }} - {{ priceRange[1] }} 元</span>
      </div>
    </div>


    <div v-if="isLoading" class="loading-mask">
      <div class="loading-content">
        <i class="el-icon-loading"></i>
        <span>数据加载中...</span>
      </div>
    </div>

    <!-- 网格视图 -->
    <div class="agricultural-grid" v-else>
      <div class="agricultural-cards">
        <el-card
          v-for="agricultural in filteredAgriculturals"
          :key="agricultural.id"
          class="agricultural-card"
          shadow="hover"
        >
          <div class="card-content">
            <div class="agricultural-image">
              <el-image
                :src="getMainImage(agricultural.imageUrl)"
                :fit="'cover'"
                :error-src="'https://picsum.photos/300/200?random=agricultural-'+agricultural.id"
                class="card-image"
                @click="viewDetail(agricultural.id)"
              ></el-image>
            </div>
            <div class="agricultural-info">
              <h3 class="agricultural-name">{{ agricultural.name }}</h3>
              <div class="agricultural-price">
                <span class="price-text">¥{{ agricultural.price }}</span> / {{ agricultural.unit }}
              </div>
              <div class="agricultural-meta">
                <span><i class="el-icon-location"></i> {{ agricultural.origin }}</span>
                <span><i class="el-icon-shopping"></i> {{ getDeptName(agricultural.deptId) || '未指定商店' }}</span>
                <span><i class="el-icon-time"></i> {{ formatDate(agricultural.createTime) }}</span>
              </div>
              <div class="agricultural-actions">
                <el-button type="primary" size="small" @click="viewDetail(agricultural.id)">
                  查看详情
                </el-button>
              </div>
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 空状态 -->
    <div class="empty-state" v-else>
      <i class="el-icon-s-home"></i>
      <p>暂无农产品数据</p>
    </div>

    <!-- 分页控件 -->
    <div class="pagination-section" v-if="!isLoading && agriculturals.length > 0">
      <el-pagination
        background
        layout="total, prev, pager, next, sizes"
        :page-sizes="[8, 12, 20, 50]"
        :page-size="pageSize"
        :total="agriculturals.length"
        @current-change="handlePageChange"
        @size-change="handleSizeChange"
      >
      </el-pagination>
    </div>

    <!-- 图片预览组件 -->
    <image-preview ref="imagePreview"></image-preview>
  </div>
</template>

<script>
import { listAgricultural } from "@/api/system/agricultural";
import { listDepts } from "@/api/system/depts";
import imagePreview from "@/components/ImagePreview";

export default {
  name: "AgriculturalProduct",
  components: {
    imagePreview
  },
  data() {
    return {
      agriculturals: [], // 所有农产品数据
      filteredAgriculturals: [], // 过滤后的农产品数据
      searchQuery: "",
      pageSize: 8,
      currentPage: 1,
      priceRange: [0, 200],
      filterByOrigin: null,
      baseUrl: process.env["VUE_APP_BASE_API"] || "",
      isLoading: true, // 加载状态
      depts: {} // 存储部门ID到名称的映射
    };
  },
  mounted() {
    this.loadAllData();
  },
  methods: {
    // 统一加载所有数据
    async loadAllData() {
      try {
        // 加载农产品数据
        const agriculturalResponse = await listAgricultural();
        this.agriculturals = agriculturalResponse.rows || [];

        // 加载部门数据
        const deptResponse = await listDepts({ pageNum: 1, pageSize: 1000 });

        let deptList = [];
        if (deptResponse.data && Array.isArray(deptResponse.data)) {
          deptList = deptResponse.data;
        } else if (deptResponse.rows && Array.isArray(deptResponse.rows)) {
          deptList = deptResponse.rows;
        } else if (Array.isArray(deptResponse)) {
          deptList = deptResponse;
        } else {
          deptList = [];
        }

        if (Array.isArray(deptList)) {
          this.depts = deptList.reduce((map, dept) => {
            const deptId = Number(dept.deptId);
            const deptName = dept.deptName || '未知部门';
            map[deptId] = deptName;
            return map;
          }, {});
        } else {
          console.warn('部门数据不是数组，无法构建映射:', deptList);
          this.depts = {};
        }

        this.updateFilteredAgriculturals();
        this.isLoading = false;
      } catch (error) {
        console.error("数据加载失败:", error);
        this.$message.error("数据加载失败，请重试");
        this.isLoading = false;
      }
    },

    // 根据部门ID获取部门名称
    getDeptName(deptId) {
      const id = Number(deptId);
      return this.depts[id] || '未指定商店';
    },

    // 搜索农产品
    searchAgricultural() {
      this.updateFilteredAgriculturals();
    },

    // 统一更新过滤后数据
    updateFilteredAgriculturals() {
      if (!this.agriculturals) return;

      let filtered = [...this.agriculturals];

      // 搜索过滤
      if (this.searchQuery) {
        const query = this.searchQuery.toLowerCase();
        filtered = filtered.filter(agricultural =>
          agricultural.name.toLowerCase().includes(query) ||
          (agricultural.origin && agricultural.origin.toLowerCase().includes(query)) ||
          (this.depts[agricultural.deptId] && this.depts[agricultural.deptId].toLowerCase().includes(query))
        );
      }

      // 按产地过滤
      if (this.filterByOrigin) {
        filtered = filtered.filter(agricultural => agricultural.origin === this.filterByOrigin);
      }

      // 按价格过滤
      filtered = filtered.filter(agricultural =>
        agricultural.price >= this.priceRange[0] && agricultural.price <= this.priceRange[1]
      );

      // 分页
      const startIndex = (this.currentPage - 1) * this.pageSize;
      const endIndex = startIndex + this.pageSize;
      this.filteredAgriculturals = filtered.slice(startIndex, endIndex);
    },

    // 图片处理方法
    getMainImage(imageUrl) {
      if (!imageUrl) return null;

      // 处理可能的多图情况
      if (imageUrl.includes(',')) {
        imageUrl = imageUrl.split(',')[0].trim();
      }

      // 动态适配开发/生产环境
      return this.getImageUrl(imageUrl);
    },

    // 统一图片URL处理
    getImageUrl(url) {
      if (process.env.NODE_ENV === 'development') {
        return `${this.baseUrl}${url}`;
      } else {
        // 开发环境默认使用85端口
        return `http://localhost:8085/dev-api${url}`;
      }
    },

    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return '';
      const date = new Date(dateString);
      return date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
    },

    // 查看详情
    viewDetail(id) {
      this.$router.push({ path: `/agriculturalsdetail/${id}` });
    },

    // 分页变化
    handlePageChange(page) {
      this.currentPage = page;
      this.updateFilteredAgriculturals();
    },

    // 每页数量变化
    handleSizeChange(size) {
      this.pageSize = size;
      this.currentPage = 1;
      this.updateFilteredAgriculturals();
    },

    // 按价格过滤
    filterByPrice() {
      this.updateFilteredAgriculturals();
    }
  }
};
</script>

<style lang="scss" scoped>
// 农产品管理页面样式
.agricultural-page {
  max-width: 1400px;
  margin: 0 auto;
  padding: 20px;
  position: relative;

  .header-section {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30px;
    padding: 20px;
    background: linear-gradient(to right, #f8f9fa, #e9ecef);
    border-radius: 12px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);

    .title-container {
      .page-title {
        font-size: 28px;
        color: #2c3e50;
        margin-bottom: 8px;
      }
    }

    .toolbar {
      display: flex;
      width: 100%;
      margin-top: 15px;

      .search-section {
        display: flex;
        flex: 1;
        max-width: 600px;

        .search-input {
          flex: 1;
          margin-right: 10px;
        }
      }
    }
  }

  .filter-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 25px;
    padding: 15px 0;
    border-bottom: 1px solid #eee;

    .filter-options {
      display: flex;
      align-items: center;
      flex: 1;

      .el-slider {
        flex: 1;
        max-width: 400px;
        margin-right: 20px;
      }

      .price-range-text {
        min-width: 120px;
        text-align: right;
      }
    }
  }

  .loading-mask {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(255, 255, 255, 0.8);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 10;

    .loading-content {
      text-align: center;

      i {
        font-size: 24px;
        color: #409EFF;
        margin-bottom: 10px;
      }

      span {
        color: #606266;
      }
    }
  }

  .agricultural-grid {
    .agricultural-cards {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
      gap: 25px;

      .agricultural-card {
        transition: all 0.3s ease;
        border-radius: 12px;
        overflow: hidden;

        &:hover {
          transform: translateY(-5px);
          box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
        }

        .card-content {
          display: flex;
          flex-direction: column;
          height: 100%;

          .agricultural-image {
            height: 200px;
            overflow: hidden;
            position: relative;

            .card-image {
              width: 100%;
              height: 100%;
              object-fit: cover;
              transition: transform 0.3s ease;

              &:hover {
                transform: scale(1.05);
              }
            }
          }

          .agricultural-info {
            padding: 20px;
            flex: 1;
            display: flex;
            flex-direction: column;

            .agricultural-name {
              margin: 0 0 10px;
              font-size: 18px;
              color: #2c3e50;
              font-weight: 500;
            }

            .agricultural-price {
              margin-bottom: 10px;

              .price-text {
                font-size: 16px;
                font-weight: bold;
                color: #e74c3c;
              }
            }

            .agricultural-meta {
              display: flex;
              flex-wrap: wrap;
              margin-bottom: 15px;
              color: #7f8c8d;
              font-size: 14px;

              span {
                margin-right: 15px;
                margin-bottom: 5px;
                display: flex;
                align-items: center;
              }

              i {
                margin-right: 5px;
              }
            }

            .agricultural-actions {
              display: flex;
              justify-content: center;
            }
          }
        }
      }
    }
  }

  .empty-state {
    text-align: center;
    padding: 50px 0;

    i {
      font-size: 48px;
      color: #909399;
      margin-bottom: 20px;
    }

    p {
      color: #606266;
      font-size: 16px;
    }
  }

  .pagination-section {
    margin-top: 30px;
    text-align: center;
  }
}

/* 隐藏图片错误图标 */
::v-deep .el-image .image-slot .el-icon-picture-outline {
  display: none !important;
}
</style>
